﻿using CefSharp;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace 千牛批量开票助手.Func
{
    internal class Configs
    {
        private static string PATH_CONFIG = $"{AppDomain.CurrentDomain.BaseDirectory}\\Config.json";
        private static string PATH_COOKIES = $"{AppDomain.CurrentDomain.BaseDirectory}\\Cookies";

        public class UsrCls
        {
            public string FUsr { get; set; }
            public string FPwd { get; set; }
        }

        public class ConfigCls
        {
            public string FUsr { get; set; }
            public string FPwd { get; set; }
            public string FInvoicePath { get; set; }
            public string FBackupPath { get; set; }
            public int FLoopTime { get; set; }
            public int FLoopQty { get; set; }
        }

        public static UsrCls GetUsr()
        {
            return new UsrCls { FUsr = "连盛旗舰店:数据", FPwd = "liansheng2022" };
        }

        /// <summary>
        /// 保存配置文件
        /// </summary>
        public static void SaveConfig(string usr, string pwd, string invoicePath, string backupPath, int loopTime, int loopQty)
        {
            using (FileStream fileStream = new FileStream(PATH_CONFIG, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                StreamWriter streamWriter = new StreamWriter(fileStream);
                streamWriter.Write(JsonConvert.SerializeObject(new ConfigCls
                {
                    FUsr = usr,
                    FPwd = pwd,
                    FInvoicePath = invoicePath,
                    FBackupPath = backupPath,
                    FLoopTime = loopTime,
                    FLoopQty = loopQty
                }));
                streamWriter.Flush();
                streamWriter.Close();
                fileStream.Close();
                fileStream.Dispose();
            }
        }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <returns></returns>
        public static ConfigCls ReadConfig()
        {
            if (File.Exists(PATH_CONFIG))
            {
                using (FileStream fileStream = new FileStream(PATH_CONFIG, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                {

                    StreamReader streamReader = new StreamReader(fileStream);
                    try
                    {
                        ConfigCls configCls = JsonConvert.DeserializeObject<ConfigCls>(streamReader.ReadToEnd());
                        streamReader.Close();
                        fileStream.Close();
                        fileStream.Dispose();
                        return configCls;
                    }
                    catch {
                        streamReader.Close();
                        fileStream.Close();
                        fileStream.Dispose();
                        try { File.Delete(PATH_CONFIG); } catch { }
                        return null;
                    }
                }
            }

            return null;
        }

        /// <summary>
        /// 保存 Cookies
        /// </summary>
        /// <param name="cookies"></param>
        public static void SaveCookies(List<Cookie> cookies)
        {
            using (FileStream fileStream = new FileStream(PATH_COOKIES, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                StreamWriter streamWriter = new StreamWriter(fileStream);
                streamWriter.Write(JsonConvert.SerializeObject(cookies));
                streamWriter.Flush();
                streamWriter.Close();
                fileStream.Close();
                fileStream.Dispose();
            }
        }

        /// <summary>
        /// 读取 Cookies
        /// </summary>
        /// <returns></returns>
        public static List<Cookie> ReadCookies()
        {
            if (File.Exists(PATH_COOKIES))
            {
                using (FileStream fileStream = new FileStream(PATH_COOKIES, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    StreamReader streamReader = new StreamReader(fileStream);
                    try
                    {
                        List<Cookie> cookies = JsonConvert.DeserializeObject<List<Cookie>>(streamReader.ReadToEnd());
                        streamReader.Close();
                        fileStream.Close();
                        fileStream.Dispose();
                        return cookies;
                    }
                    catch {
                        streamReader.Close();
                        fileStream.Close();
                        fileStream.Dispose();
                        try { File.Delete(PATH_COOKIES); } catch { }
                        return null; 
                    }
                }
            }

            return null;
        }

        public static string GlobalJS()
        {
            return @"
                // 输入事件
                const __InputEvent__ = (inputObj, value) => {
                    inputObj.value = value;
            
                    let event = new Event('input', { bubbles: true });
                    let tracker = inputObj._valueTracker;
                    if (tracker) tracker.setValue('');
                    inputObj.dispatchEvent(event);
                };

                // 输入订单编号
                const InputOrderNum = (num) => {
                    let ctrls = document.getElementsByClassName('invoice-conditions-label');
                    for (i = 0; i < ctrls.length; i++) {
                        if (ctrls[i].innerHTML == '订单编号') {
                            let input = ctrls[i].parentNode.getElementsByTagName('input')[0];
                            
                            __InputEvent__(input, num);
            
                            document.getElementsByClassName('condition_btn-HfaSh')[0].getElementsByTagName('button')[0].click();
                            return;
                        }
                    }
                };

                // 获取查询结果
                const GetSearchCount = () => {
                    let content = document.getElementsByClassName('invoice-search-table-middle')[0].getElementsByClassName('left-label')[0].innerHTML;
                    return parseInt(/\d+/g.exec(content)[0]);
                };

                // 读取是否存在爬虫检验
                const GetIdentifyCheck = () => {
                    return document.getElementById('baxia-dialog-content') == null;
                };

                // 点击同意
                const ClickAllow = async (amount) => {
                    const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));

                    let rows = document.getElementsByClassName('invoice-search-table-middle')[0].parentNode.parentNode.getElementsByClassName('ant-table-content')[0].getElementsByClassName('ant-table-body')[0].getElementsByClassName('ant-table-row-level-0');
                    
                    let orderNum = rows[0].getElementsByTagName('td')[1].getElementsByTagName('span')[0].innerHTML;
                    let olAmount = rows[0].getElementsByTagName('td')[8].innerHTML.replace('￥', '');
                    let status = true;

                    // 当发票金额相同时才执行上传操作
                    if (parseFloat(amount) == parseFloat(olAmount)) {
                        let ctrls = rows[0].getElementsByTagName('td')[9].getElementsByTagName('a');
                        let flag = -1;
                        for (i = 0; i < ctrls.length; i++) {
                            if(ctrls[i].innerHTML == '同意') {
                                flag = i;
                                break;
                            }
                        }
                        
                        if (flag > 0) {
                            ctrls[flag].click();

                            // 0.5 秒后在弹出的对话框里选择[在[待录入列表]中手动上传发票]类型
                            await sleep(500);
                            document.getElementsByClassName('next-dialog')[0].getElementsByTagName('label')[1].click();
                            await sleep(1000);
                            document.getElementsByClassName('next-dialog')[0].getElementsByTagName('button')[0].click(); // 确定
                            // document.getElementsByClassName('next-dialog')[0].getElementsByTagName('button')[1].click(); // 取消
                        } else {
                            status = false;
                        }
                    }

                    return JSON.stringify({ 'orderNum': orderNum, 'amount': olAmount, 'status': status });
                };

                // 点击录入发票
                const ClickInput = async (count) => {
                    const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));

                    let rows = document.getElementsByClassName('invoice-search-table-middle')[0].parentNode.parentNode.getElementsByClassName('ant-table-content')[0].getElementsByClassName('ant-table-body')[0].getElementsByClassName('ant-table-row-level-0');
                    let ctrls = rows[0].getElementsByTagName('td')[8].getElementsByTagName('a');
                    let flag = -1;
                    for (i = 0; i < ctrls.length; i++) {
                        if(ctrls[i].innerHTML == '录入发票') {
                            flag = i;
                            break;
                        }
                    }
                    ctrls[flag].click();

                    // 0.5 秒后在弹出的对话框里插入发票
                    await sleep(500);

                    // 根据发票数量创建对应的输入框
                    for (i = 0; i < count-1; i++) {
                        document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=""bodyContent""]')[0].scrollTo(0, 50000);
                        await sleep(500);
                        document.getElementsByClassName('next-dialog')[0].querySelectorAll('span[class*=""handleBtn""]')[0].click();
                        await sleep(500);
                    }
                };

                // 点击上传
                const UploadClick = async (i) => {
                    const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));
    
                    document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=""bodyContent""]')[0].querySelectorAll('div[class*=""invoiceFormBlock""')[i].scrollIntoView({ block: 'start' });
                    await sleep(500);
                    document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=""bodyContent""]')[0].querySelectorAll('div[class*=""invoiceFormBlock""')[i].getElementsByTagName('button')[0].click();
                    await sleep(500);
                };

                // 输入发票信息
                const InputInvoiceInfo = (i, amount) => {
                    // 核实上传后的发票代码和发票号码是否自动填写, 如果没有则需要人工处理
                    let taxCode = document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=""bodyContent""]')[0].querySelectorAll('div[class*=""invoiceFormBlock""')[0].querySelectorAll('div[class*=""form-item""]')[3].getElementsByTagName('input')[0].value;
                    let taxOrderNum = document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=""bodyContent""]')[0].querySelectorAll('div[class*=""invoiceFormBlock""')[0].querySelectorAll('div[class*=""form-item""]')[4].getElementsByTagName('input')[0].value;

                    if (taxCode == '' | taxOrderNum == '') return false;

                    // 输入发票信息
                    let title = document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=""bodyContent""]')[0].querySelectorAll('div[class*=""invoiceFormBlock""')[0].querySelectorAll('div[class*=""form-item""]')[5].getElementsByTagName('input')[0].value;
                    let taxNum = '';

                    if (document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=""bodyContent""]')[0].querySelectorAll('div[class*=""invoiceFormBlock""')[0].querySelectorAll('div[class*=""form-item""]').length > 8) {
                        taxNum = document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=""bodyContent""]')[0].querySelectorAll('div[class*=""invoiceFormBlock""')[0].querySelectorAll('div[class*=""form-item""]')[8].getElementsByTagName('input')[0].value;
                    }

                    // 如果税号为空, 则说明是个人类型, 需要选择个人类型
                    if (taxNum == '') {
                        document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=""bodyContent""]')[0].querySelectorAll('div[class*=""invoiceFormBlock""')[i].querySelectorAll('div[class*=""form-item""]')[2].querySelectorAll('span[class*=""next-radio-label""')[0].click();
                    }

                    // 第二张开始的发票基本信息与第一张保持一致
                    if (i > 0) {
                        let inputTitle = document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=""bodyContent""]')[0].querySelectorAll('div[class*=""invoiceFormBlock""')[i].querySelectorAll('div[class*=""form-item""]')[5].getElementsByTagName('input')[0];
                        __InputEvent__(inputTitle, title);

                        let inputTaxNum = document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=""bodyContent""]')[0].querySelectorAll('div[class*=""invoiceFormBlock""')[i].querySelectorAll('div[class*=""form-item""]')[8].getElementsByTagName('input')[0];
                        __InputEvent__(inputTaxNum, taxNum);
                    }

                    // 输入发票金额
                    let inputAmount = document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=""bodyContent""]')[0].querySelectorAll('div[class*=""invoiceFormBlock""')[i].querySelectorAll('span[class=""form-input-custom""]')[0].getElementsByTagName('input')[0];
                    if (inputAmount.value == '') __InputEvent__(inputAmount, amount);

                    return true;
                };

                // 点击关闭对话框
                const ClickDialogClose = () => {
                    document.getElementsByClassName('next-dialog')[0].getElementsByClassName('next-dialog-close')[0].click()
                };

                // 点击完成开票
                const ClickDialogFinish = () => {
                    document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=""dialogFooter""]')[0].getElementsByTagName('button')[1].click()
                };
            ";
        }
    }
}
